package com.gds.config.exception;


import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.gds.utils.BizException;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
class HandlerException extends ExceptionHandlerExceptionResolver {

    @Override
    public ModelAndView doResolveHandlerMethodException(HttpServletRequest request,

                                                        HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) {

        ModelAndView mv = new ModelAndView();
        BizException ex = null;
        if (exception instanceof BizException) {
            ex = (BizException) exception;
            Map map = new HashMap();
            map.put("code", ex.getErrorCode() != null && !(ex.getErrorCode() + "").equals("200")?ex.getErrorCode():"0000");
            map.put("msg", ex.getMsg());
            map.put("success", false);
            FastJsonJsonView view = new FastJsonJsonView();
            view.setAttributesMap(map);
            mv.setView(view);
        }
        return mv;
    }
}
